package com.linjiahao.userCenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linjiahao.commonUtil.Redis.RedisService;
import com.linjiahao.commonUtil.Security.RSAUtil;
import com.linjiahao.commonUtil.base.JWTUtil;
import com.linjiahao.commonall.base.ResultMap;
import com.linjiahao.commonall.exception.GlobalErrorMessage;
import com.linjiahao.commonall.exception.WebChatException;
import com.linjiahao.userCenter.common.BaseConstant;
import com.linjiahao.userCenter.common.ErrorMessage;
import com.linjiahao.userCenter.domain.ChatUserInfo;
import com.linjiahao.userCenter.mapper.ChatUserInfoMapper;
import com.linjiahao.userCenter.service.ChatUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @ClassName ChatUserInfoServiceImpl
 * @Description: 用户服务抽象实现类
 * @Author linjiahao
 * @Date 29/12/2021
 **/
@Service
@Slf4j
public class ChatUserInfoServiceImpl extends ServiceImpl<ChatUserInfoMapper, ChatUserInfo> implements ChatUserInfoService {

    @Resource
    private RedisService redisService;

    @Value("${rsa.PUBLIC_KEY}")
    private String publicKey;


    @Override
    public ResultMap userLogin(String phone, String code, HttpServletResponse response) {
        //校验验证码
        String authCode = redisService.getString(String.format(BaseConstant.MSM_PHONE_CODE_KEY, phone));
        if(StringUtils.isNotBlank(authCode)){
            if(!authCode.equals(code)){
                throw new WebChatException(ErrorMessage.VERIFICATION_CODE_ERROR.getErrorCode(),ErrorMessage.VERIFICATION_CODE_ERROR.getMessage());
            }
        }else {
            throw new WebChatException(ErrorMessage.VERIFICATION_CODE_HAS_EXPIRED.getErrorCode(),ErrorMessage.VERIFICATION_CODE_HAS_EXPIRED.getMessage());
        }
        ChatUserInfo chatUserInfo = this.baseMapper.selectOne(new QueryWrapper<ChatUserInfo>().lambda().eq(ChatUserInfo::getPhone, phone));
        String token = "";
        if(chatUserInfo == null){
            //用户新增
            ChatUserInfo info = new ChatUserInfo().getInitUserInfo(phone);
            this.baseMapper.insert(info);
            //生成token
            token = JWTUtil.generateTokenWithUserId(info.getUserId());
            chatUserInfo = info;
        }else {
            token = JWTUtil.generateTokenWithUserId(chatUserInfo.getUserId());
        }
        redisService.hset(BaseConstant.USER_LOGIN_SUCCESS,String.valueOf(chatUserInfo.getUserId()),chatUserInfo,7200);
        response.setHeader("Access-Control-Expose-Headers",BaseConstant.HEADER_TOKEN_KEY);
        response.setHeader(BaseConstant.HEADER_TOKEN_KEY,token);
        return ResultMap.ok().data("userInfo",chatUserInfo);
    }

    @Override
    public void logout(String authToken) {
        if(StringUtils.isBlank(authToken)){
            throw new WebChatException(GlobalErrorMessage.ILLEGAL_REQUEST.getErrorCode(),GlobalErrorMessage.ILLEGAL_REQUEST.getMessage());
        }
        Long userId = JWTUtil.getUserId(authToken);
        redisService.hdel(BaseConstant.USER_LOGIN_SUCCESS,String.valueOf(userId));
    }

    @Override
    public ResultMap getUserInfoBytoken(String authToken) {
        if(StringUtils.isBlank(authToken)){
            throw new WebChatException(GlobalErrorMessage.ILLEGAL_REQUEST.getErrorCode(),GlobalErrorMessage.ILLEGAL_REQUEST.getMessage());
        }
        ChatUserInfo info = (ChatUserInfo)redisService.hget(BaseConstant.USER_LOGIN_SUCCESS, "");
        if(!Optional.ofNullable(info).isPresent()){
            throw new WebChatException(GlobalErrorMessage.TOKEN_IS_NOT_VALIDATE.getErrorCode(),GlobalErrorMessage.TOKEN_IS_NOT_VALIDATE.getMessage());
        }
        return ResultMap.ok().data("userInfo", info);
    }

    @Override
    public ResultMap chatEncrypt(String authToken, HttpServletResponse response) {
        if(StringUtils.isBlank(authToken)){
            throw new WebChatException(GlobalErrorMessage.ILLEGAL_REQUEST.getErrorCode(),GlobalErrorMessage.ILLEGAL_REQUEST.getMessage());
        }
        Long userId = JWTUtil.getUserId(authToken);
        Object o = redisService.hget(BaseConstant.USER_LOGIN_SUCCESS, String.valueOf(userId));
        if(!Optional.ofNullable(o).isPresent()){
            throw new WebChatException(GlobalErrorMessage.TOKEN_IS_NOT_VALIDATE.getErrorCode(),GlobalErrorMessage.TOKEN_IS_NOT_VALIDATE.getMessage());
        }
        String encrypt = null;
        try {
            encrypt = RSAUtil.encryptByPublicKey(String.valueOf(userId), publicKey);
        } catch (Exception e) {
            log.error("用户：{}，RSA加密失败：{}",userId,e);
            return ResultMap.error();
        }
        response.setHeader("Access-Control-Expose-Headers",BaseConstant.HEADER_CHAT_TOKEN_KEY);
        response.setHeader(BaseConstant.HEADER_CHAT_TOKEN_KEY,encrypt);
        return ResultMap.ok();
    }

}
